# !/usr/bin/env python
# coding=utf-8
# @Time    : 2021-2-5 21:15
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/SeleniumCrapy.git
# @File    : my_rsa.py
# @Software: PyCharm
# @Version: 2.7.5
import base64

from Crypto.Hash import SHA256, SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5


def sign(data, priKey):
	key = RSA.importKey(priKey)
	h = SHA.new(data.encode("utf-8"))
	signer = PKCS1_v1_5.new(key)
	signature = signer.sign(h)
	return base64.b64encode(signature)

class SignatureAndVerification(object):
	"""RSA签名和验签"""

	@classmethod
	def data_processing(cls, data):
		"""
		:param data: 需要签名的数据，字典类型
		:return: 处理后的字符串，格式为：参数名称=参数值，并用&连接
		"""
		return data
		# if "sign" in data:
		# 	del data["sign"]
		# if "sign_type" in data:
		# 	del data["sign_type"]
		# dataList = []
		# for key in sorted(data):
		# 	if data[key]:
		# 		dataList.append("%s=%s" % (key, data[key]))
		# return "&".join(dataList).strip()

	@classmethod
	def rsa_sign_private(cls, data, private_key):
		"""
		RSA私钥签名
		:param data: 明文数据
		:param private_key: RSA签名需要的私钥
		:return: 签名后的字符串sign
		"""
		rsa_key = RSA.importKey(private_key)
		signer = PKCS1_v1_5.new(rsa_key)
		digest = SHA256.new()
		digest.update(cls.data_processing(data).encode("utf8"))
		sign = signer.sign(digest)
		signature = base64.b64encode(sign)
		return str(signature, encoding="utf-8")

	@classmethod
	def rsa_sign_public(cls, data, public_key, signature):
		"""
		RSA公钥验签
		:param data: 明文数据
		:param public_key: RSA验签需要的公钥
		:param signature: 接收到的sign签名
		:return: 验签结果,布尔值
		"""
		rsa_key = RSA.importKey(public_key)
		verifier = PKCS1_v1_5.new(rsa_key)
		digest = SHA256.new()
		digest.update(cls.data_processing(data).encode("utf-8"))
		# 因为签名时对签名值进行过base64编码，所以验签时需要解码
		is_verify = verifier.verify(digest, base64.b64decode(signature))
		return is_verify